package com.cnpc.ds.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.cnpc.ds.service.impl.user.KyUserUtil;
import com.cnpc.eisc.base.pojo.User;
import com.cnpc.eisc.base.util.UserResolverUtil;
import org.springframework.core.MethodParameter;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: leemeea
 * @Date: 2021/7/9 10:04
 */
@Service("userResolver")
public class UserResolver implements HandlerMethodArgumentResolver {

    //token缓存
    private static Map<String,User> tokenCache=new HashMap<>();
    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterType().isAssignableFrom(User.class);
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter,
                                  ModelAndViewContainer modelAndViewContainer,
                                  NativeWebRequest nativeWebRequest,
                                  WebDataBinderFactory webDataBinderFactory) {
        User user =UserResolver.getUser();
        return user;
    }

    public static User getUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String authorization = request.getHeader("Authorization");
        if(StrUtil.isEmpty(authorization)){
            return null;
        }
        //缓存token
        User user = tokenCache.get(authorization);
        if(user==null){
            //真实获取用户
            user = getUser(authorization);
            if(user!=null){
                tokenCache.put(authorization,user);
            }
        }
        return user;
    }

    //todo 多系统获取用户 （以后只需要修改此处）
    public static User getUser(String token){
        Environment environment = SpringUtil.getBean(Environment.class);
        String env = environment.getProperty("spring.profiles.active");
        //测试
//        env="rdc";
        //新疆油田
        if ("ky".equals(env)) {
            return KyUserUtil.getUser(token);
        }
        //科研和eisc
        else {
            return UserResolverUtil.getUser(token);
        }
    }
}
